package address

import (
	"encoding/json"
	"sweetsunnyflower/pkg/app"
	"sweetsunnyflower/pkg/database"
	"sweetsunnyflower/pkg/logger"
	"sweetsunnyflower/pkg/paginator"
	"sweetsunnyflower/pkg/redis"
	"time"

	"github.com/gin-gonic/gin"
)

const CACHE_KEY_ADDRESS = "addresses"

func Get(idstr string) (address Address) {
	database.DB.Where("id", idstr).First(&address)
	return
}

func GetBy(field, value string) (address Address) {
	database.DB.Where("? = ?", field, value).First(&address)
	return
}

func All() (addresses []Address) {
	database.DB.Find(&addresses)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(Address{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

func Paginate(c *gin.Context, perPage int) (addresses []Address, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(Address{}),
		&addresses,
		app.V1URL(database.TableName(&Address{})),
		perPage,
	)
	return
}

func GetByCache() ([]*ResponseAddress, error) {

	cacheAddress := redis.Redis.Get(CACHE_KEY_ADDRESS)

	var addresses []*ResponseAddress

	if cacheAddress == "" || cacheAddress == "null" {
		logger.InfoString("address", "GetByCache", "cache is empty")
		addresses = GetAddresses()
		data, err := json.Marshal(addresses)
		if err != nil {
			return nil, err
		}
		redis.Redis.Set(CACHE_KEY_ADDRESS, data, time.Hour*3600)
	} else {
		logger.InfoString("address", "GetByCache", "cache is not empty:"+cacheAddress)
		err := json.Unmarshal([]byte(cacheAddress), &addresses)
		if err != nil {
			return nil, err
		}
	}

	return addresses, nil
}

func GetAddresses() []*ResponseAddress {
	addresses := All()

	var responseData []*ResponseAddress

	for _, item := range addresses {

		var children []*ResponseAddress

		for _, child := range addresses {
			if item.ID != child.ID {
				children = append(children, &ResponseAddress{
					ID:   child.ID,
					Name: child.Name,
				})
			}
		}

		responseData = append(responseData, &ResponseAddress{
			ID:       item.ID,
			Name:     item.Name,
			Children: children,
		})
	}

	return responseData
}
